import cv2
import os


def split_image_into_tiles(image_path, output_dir, tile_size=256):
    # 创建输出目录
    os.makedirs(output_dir, exist_ok=True)

    # 加载图像
    image = cv2.imread(image_path)
    if image is None:
        raise FileNotFoundError(f"无法打开图像文件：{image_path}")

    # 获取图像尺寸
    h, w = image.shape[:2]

    # 分割图像并保存每个小块
    for row in range(0, h, tile_size):
        for col in range(0, w, tile_size):
            # 提取当前块
            tile = image[row:row + tile_size, col:col + tile_size]

            # 生成文件名，行数(row)在前，列数(col)在后
            tile_filename = f"tile_{row // tile_size}_{col // tile_size}.png"

            # 保存小块图像
            cv2.imwrite(os.path.join(output_dir, tile_filename), tile)


image_path = r'E:\wafer52\11867_256nm\S11867M1-80_tr1-tc1.png'
output_dir = r'E:\wafer52\11867_256nm_split'

split_image_into_tiles(image_path, output_dir, tile_size=128)

print(f"Tiles saved to {output_dir}")